<?php


namespace app\backstage\controller;


use think\Controller;
use think\Db;

class Recovery extends Controller
{
    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => []],
    ];

    /**
     * 回收报表
     * @return mixed
     */
    public function index()
    {
        $agentId = request()->_role->alias == 'agent' ? request()->_user->id : 0;
        $Account = \think\facade\App::model('Account', 'logic');
        $channels = $Account->getChannels($agentId);

        $this->assign('channels', $channels);
        $this->assign('role_name', request()->_role->alias);
        return $this->fetch();
    }

    public function dataList()
    {
        $table = "rp_recovery_channel";
        $tableDetail = "rp_recovery_channel_detail";
        $channelId = input("channel_id");
        $startDate = input("start_date");
        $endDate = input("end_date");
        $page = input('page', 1);
        $limit = input('limit', 10);
        $mgUid = request()->_user->id;//后台账号id
        $where = [];
        if (request()->_role->alias == 'channel') {
            $channelId = $mgUid;
        } elseif (request()->_role->alias == 'agent') {
            //是下属账号
            if ($channelId != '') {
                $parentId = \app\backstage\model\ManagerUser::where("id", $channelId)->value('parent_id');
                if ($parentId != $mgUid) {
                    $this->error('代理id异常');
                }
            } else {
                $table = "rp_recovery_agent";
                $tableDetail = "rp_recovery_agent_detail";
            }
        } else {
            $this->error('访问角色异常');
        }

        $costAllWhere = [];
        if ($table == 'rp_recovery_agent') {
            $where[] = ['uid', '=', $mgUid];
            $costAllWhere[] = ['agent_id', '=', $mgUid];
        } else {
            $where[] = ['uid', '=', $channelId];
            $costAllWhere[] = ['channel_id', '=', $channelId];
        }
        if ($startDate != '') {
            $where[] = ['rp_date', '>=', $startDate];
            $costAllWhere[] = ['cost_date', '>=', $startDate];
        }
        if ($endDate != '') {
            $where[] = ['rp_date', '<=', $endDate];
            $costAllWhere[] = ['cost_date', '<=', $endDate];
        }

        $list = Db::table($table)->where($where)->order("rp_date desc")->page($page,$limit)->select();
        $today = date("Y-m-d");
        foreach ($list as $k => $v) {
            $endDate = date("Y-m-d", strtotime($v['rp_date'] . ' +29 days'));//包含当天，后续30天，付费用户
            if ($table == 'rp_recovery_agent') {
                $list[$k]['cost'] = Db::table("rp_cost_manual")->where("agent_id", $mgUid)->where("cost_date", $v['rp_date'])->where("type",1)->sum('money') ?? 0;//成本
                $list[$k]['pu_num'] = Db::table("pay_order_success")->where('agent_id', $mgUid)->where("user_source_date", $v['rp_date'])->where("create_date", "<=", $endDate)->group("uid")->count();
            } else {
                $list[$k]['cost'] = Db::table("rp_cost_manual")->where("channel_id", $channelId)->where("cost_date", $v['rp_date'])->where("type",1)->sum('money') ?? 0;//成本
                $list[$k]['pu_num'] = Db::table("pay_order_success")->where('channel_id', $channelId)->where("user_source_date", $v['rp_date'])->where("create_date", "<=", $endDate)->group("uid")->count();
            }
            $list[$k]['hs_rate'] = getQuotient($v['money'], $list[$k]['cost'], 2, 'm', 100) . '%';
            $details = Db::table($tableDetail)->where("uid", $v['uid'])->where("rp_date", '=', $v['rp_date'])->select();
            $indexArr = array_column($details, null, 't_index');

            for ($i = 1; $i <= 30; $i++) {
                $dayIndex = $i - 1;
                $daysLater = date('Y-m-d', strtotime($v['rp_date'] . "+{$dayIndex} days"));
                if (isset($indexArr[$i])) {
                    $fastMoney = Db::table($tableDetail)->where("uid", $v['uid'])->where("rp_date", '=', $v['rp_date'])->where("t_index", "<=", $i)->sum('money') ?? 0;
                    $list[$k]["rate_recovery_{$i}"] = $list[$k]['cost'] > 0 ? getQuotient($fastMoney, $list[$k]['cost'], 2, 'm', 100) : 0;
                    $list[$k]["rate_recovery_{$i}"] = $list[$k]["rate_recovery_{$i}"] . "%";
                    $list[$k]["increase_{$i}"] = getQuotient($indexArr[$i]['money'], 100);
                } else {
                    //任务里money为0会不记录，所以直接覆盖小于今日为0
                    if ($daysLater <= $today) {
                        $list[$k]["increase_{$i}"] = "0";
                        $list[$k]["rate_recovery_{$i}"] = "0%";
                    } else {
                        $list[$k]["increase_{$i}"] = "-";
                        $list[$k]["rate_recovery_{$i}"] = "-";
                    }
                }
            }
            $list[$k]['money'] = moneyFormat($v['money']);
            $list[$k]['nu_money'] = moneyFormat($v['nu_money']);
            $list[$k]['cost'] = moneyFormat($list[$k]['cost']);
            $list[$k]['fast_money'] = moneyFormat($v['fast_money']);
        }
        $count = Db::table($table)->where($where)->count();

        $totalRow['cost'] = Db::table("rp_cost_manual")->where($costAllWhere)->sum('money') ?? 0;

        $sumFind = Db::table($table)->where($where)->field("sum(money) money,sum(nu_money) nu_money,sum(fast_money) fast_money")->find();
        if ($sumFind){
            $money = $sumFind['money'] ?? 0;
            $nu_money = $sumFind['nu_money'] ?? 0;
            $fast_money = $sumFind['fast_money'] ?? 0;
        }else{
            $money = 0;
            $nu_money = 0;
            $fast_money = 0;
        }
        $totalRow['hs_rate'] = getQuotient($money, $totalRow['cost'], 2, 'm', 100) . '%';
        $totalRow['cost'] = moneyFormat($totalRow['cost']);
        $totalRow['money'] = moneyFormat($money);
        $totalRow['nu_money'] = moneyFormat($nu_money);
        $totalRow['fast_money'] = moneyFormat($fast_money);


        if ($count === null) {
            return json(['code' => 1, 'msg' => 'ok', 'data' => $list]);
        }

        return json(['code' => 1, 'msg' => 'ok', 'count' => $count, 'data' => $list, 'totalRow' => $totalRow]);
    }

    public function dataSumInfo()
    {
        return sucJson([]);
    }
}